package com.bonc.web.xss;


import com.bonc.util.exception.BusinessException;
import com.bonc.util.response.CommResponseEnum;
import org.apache.commons.text.StringEscapeUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
  * @Description: 用于普通多参数的HttpServletRequest,创建内部类XssHttpServletRequestWrapper，该类继承HttpServletRequestWrapper，
  *               是HttpServletRequest的装饰类，用来改变HttpServletRequest的状态，从而达到对请求内容的过滤的功能
  * @Author: ChenZhiXiang
  * @CreateDate: 2019/3/4 0004 17:52
  * @Version: 1.0
* */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    @Override
    public String getHeader(String name) {
        return StringEscapeUtils.escapeHtml4(super.getHeader(name));
    }

    /**
     * URL参数值获取
     * @return
     */
    @Override
    public String getQueryString() {
        return super.getQueryString() == null ? "" : SequenceTool.xssEncode(super.getQueryString()).toString();
    }

    @Override
    public String getParameter(String name) {
        return StringEscapeUtils.escapeHtml4(super.getParameter(name));
    }

    @Override
    public String[] getParameterValues(String name) {

        String[] values = super.getParameterValues(name);
        if (values != null) {
            int length = values.length;
            String[] escapseValues = new String[length];
            SensitivewordFilter filter = new SensitivewordFilter();
            for (int i = 0; i < length; i++) {
                //判断是否包含敏感字符
                if(filter.getSensitiveWord(values[i],1).size()>0){
                    throw new BusinessException(CommResponseEnum.APIERROR6);
                }
                escapseValues[i] = SequenceTool.xssEncode(values[i]).toString();
            }
            return escapseValues;
        }
        return super.getParameterValues(name);
    }

}
